from django.db import models

# Create your models here.

class UserInfo(models.Model):
    '''
    用户表
    '''
    username = models.CharField(verbose_name="用户名", max_length=32)
    password = models.CharField(verbose_name="密码", max_length=64)
    email = models.EmailField()
    # blank = True 表示表单允许为空 null=True 表示数据库的该字段可以为空
    roles = models.ManyToManyField(verbose_name="拥有角色", to="Role", blank=True)
    ctime = models.DateTimeField(verbose_name='时间', auto_now_add=True)

    #admin声明表名
    class Meta:
        verbose_name_plural = "用户表"

    def __str__(self):
        return "{}".format(self.username)


class Role(models.Model):
    '''
    角色表
    '''
    caption = models.CharField(verbose_name="角色名称", max_length=32)
    permissions = models.ManyToManyField(verbose_name="具有的所有权限", to="Permission", blank=True)
    ctime = models.DateTimeField(verbose_name='时间', auto_now_add=True)

    class Meta:
        verbose_name_plural = "角色表"

    def __str__(self):
        return "{}".format(self.caption)

class Permission(models.Model):
    '''
    权限表
    '''
    caption = models.CharField(verbose_name="权限名", max_length=32)
    url = models.CharField(verbose_name="含正则的URL", max_length=128, blank=True, null=True)
    code = models.CharField(verbose_name="权限代码", max_length=64)
    menu_gp = models.ForeignKey(verbose_name="组内的权限ID（null表示菜单）", to="Permission",
                                related_name="p1", null=True, blank=True)
    group = models.ForeignKey(verbose_name='所属菜单组',to="Group")
    ctime = models.DateTimeField(verbose_name='时间', auto_now_add=True)

    class Meta:
        verbose_name_plural = "权限表"

    def __str__(self):
        return "{}".format(self.caption)


class Menu(models.Model):
    '''
    菜单目录结构表
    '''
    caption= models.CharField(verbose_name='菜单', max_length=32)
    parent = models.ForeignKey(verbose_name='菜单父ID', to='Menu', blank=True, null=True)

    class Meta:
        verbose_name_plural = "菜单表"

    def __str__(self):
        menu_list = [self.caption, ]
        parent = self.parent
        while True:
            if parent:
                menu_list.append(parent.caption)
                parent = parent.parent
            else:
                break
        menu_list.reverse()
        return '-'.join(menu_list)

class Group(models.Model):
    '''
    权限组
    '''
    caption = models.CharField(verbose_name='组名称', max_length=16)
    menu = models.ForeignKey(verbose_name='所属菜单', to='Menu', blank=True, null=True)

    class Meta:
        verbose_name_plural = "权限组"

    def __str__(self):
        return "{}".format(self.caption)
